package org.zjsru.order.web;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.zjsru.order.pojo.Order;
import org.zjsru.order.pojo.User;
import org.zjsru.order.service.OrderService;
import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.zjsru.order.service.OrderServiceFeign;
import org.zjsru.order.service.ProductFeignClient;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private UserClient userClient; // 注入 UserClient

    @Autowired
    private OrderService orderService;
    //@Autowired
    //RestTemplate restTemplate ;
    //@Autowired
    //NacosServiceDiscovery serviceDiscovery ;
    @Qualifier("org.zjsru.order.service.ProductFeignClient")
    @Autowired
    private ProductFeignClient productFeignClient; // 注入 ProductFeignClient

    @Autowired
    OrderServiceFeign orderServiceFeign ;

    /**
     * 根据ID查询订单
     */
    @GetMapping("/{id}")
    public Order getOrderById(@PathVariable Long id) {
        return orderService.queryOrderById(id);
    }

    /**
     * 根据用户ID查询订单列表
     */
    @GetMapping("/user/{userId}")
    public List<Order> getOrdersByUserId(@PathVariable Long userId) {
        return orderService.getOrdersByUserId(userId);
    }

    /**
     * 更新订单状态为已支付
     */
    @PostMapping("/{orderId}/pay")
    public boolean updateOrderStatus(@PathVariable Long orderId) {
        log.info("更新订单状态为已支付，订单ID: {}", orderId);
        return orderService.updateOrderStatus(orderId, 1);
    }

    /**
     * 取消订单
     */
    @PostMapping("/{orderId}/cancel")
    public Map<String, Object> cancelOrder(@PathVariable Long orderId) {
        Map<String, Object> result = new HashMap<>();
        boolean success = orderService.cancelOrder(orderId);
        result.put("success", success);
        result.put("message", success ? "订单取消成功" : "订单取消失败");
        return result;
    }

    @PostMapping("/create")
    public Map<String, Object> createOrder(
            @RequestParam("userId") Long userId,
            @RequestParam("productId") Long productId,
            @RequestParam("count") Integer count
    ) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 1. 调用用户服务验证用户
            User userInfo = userClient.getUserInfo(userId);
            if (userInfo == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }

            // 2. 创建订单对象
            Order order = new Order();
            order.setUserId(userId);
            order.setProductId(productId);
            order.setQuantity(count);
            
            // 3. 调用订单服务创建订单（包含库存扣减）
            Order createdOrder = orderService.createOrder(order);
            
            result.put("success", true);
            result.put("message", "订单创建成功");
            result.put("data", createdOrder);
            log.info("订单创建成功，订单ID: {}, 用户: {}", createdOrder.getId(), userInfo.getUsername());
            
        } catch (Exception e) {
            log.error("订单创建失败", e);
            result.put("success", false);
            result.put("message", "订单创建失败：" + e.getMessage());
        }
        return result;
    }

/*
    @GetMapping("/{userId}")
    public Order findOrderByUserId(@PathVariable("userId") Long userId){
        return null;
    }
*/
}
